﻿using Abp.Authorization;
using Abp.Linq.Expressions;
using Abp.UI;
using Basefr.App;
using Microsoft.AspNetCore.Mvc;
using Paas.App.Interface.Meta.Dtos;
using Paas.App.Interface.Meta.Messages;
using Paas.App.Interface.Meta;
using Paas.App.Interface.MetaForms;
using Paas.App.Interface.MetaForms.Dtos;
using Paas.App.Interface.MetaForms.Messages;
using Paas.Core;
using Paas.Core.Const.Enums;
using Paas.Core.Meta.Entities;
using Paas.Core.MetaForms.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Paas.App.Interface.MetaFormFields;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using MySqlX.XDevAPI.Common;

namespace Paas.App.MetaForms
{
    [Route("metaForms-metaFormField")]

    [AbpAuthorize()]
    public class MetaFormFieldAppService : AppService, IMetaFormFieldAppService
    {
        private readonly IMainRepository<MetaFormField, Guid> _metaFormFieldRepo;
        private readonly IMainRepository<MetaField, Guid> _metaFieldRepo;


        public MetaFormFieldAppService(IMainRepository<MetaFormField, Guid> metaFormFieldRepo, IMainRepository<MetaField, Guid> metaFieldRepo)
        {
            _metaFormFieldRepo = metaFormFieldRepo;
            _metaFieldRepo = metaFieldRepo;
        }

        [HttpPost(nameof(SaveMetaFormField))]
        public async Task<SaveMetaFormFieldOutput> SaveMetaFormField(SaveMetaFormFieldInput input)
        {
            if (input == null) throw new UserFriendlyException("保存失败：input为空！");

            #region 更新
            if (input.Item?.Id != null && input.Item?.Id != Guid.Empty)
            {
                //var entity = ObjectMapper.Map<MetaFormField>(input.Item);
                var uData = await _metaFormFieldRepo.GetAsync(input.Item.Id);
                if (uData == null) throw new UserFriendlyException("未找到需要更新的对象！");

                //需要更新的字段
                uData.ReLabel = input.Item.ReLabel;
                uData.SortNum= input.Item.SortNum;
                uData.IsLike=input.Item.IsLike;

                await _metaFormFieldRepo.UpdateAsync(uData);
                return new SaveMetaFormFieldOutput();
            }
            #endregion

            //设置一些默认的值

            #region 新增
            ////判断是否有数据
            if (input.FormFields?.Count>0)
            {
                //表单字段全部删除，重新增加
                //    await _metaFormFieldRepo.HardDeleteAsync(p => p.MetaFormId==input.MetaFormId);//硬删除

                //查询表单字段同一formid的最大SortNum值,没有则=0
                var maxSortNum = _metaFormFieldRepo.GetAllList(p => p.MetaFormId== input.MetaFormId)?.MaxBy(p => p.SortNum)?.SortNum??0;
                foreach (var item in input.FormFields)
                {
                    var metaField = _metaFieldRepo.FirstOrDefault(p => p.Id.ToString()==item);
                    if (metaField != null)
                    {
                        maxSortNum++;
                        var entity = new MetaFormField()
                        {
                            MetaFormId=input.MetaFormId,
                            MetaFieldId=metaField.Id,
                            //新增时默认与原字段名称相同
                            ReLabel=metaField.Label,
                            //顺序编号
                            SortNum=maxSortNum
                        };
                        await _metaFormFieldRepo.InsertAsync(entity);
                    }
                }
            }
            #endregion
            return new SaveMetaFormFieldOutput();
        }

        [HttpPost(nameof(SearchMetaFormField))]
        public async Task<SearchMetaFormFieldOutput> SearchMetaFormField(SearchMetaFormFieldInput input)
        {
            Expression<Func<MetaFormField, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.ReLabel))
            {
                predicate = predicate.And(p => p.ReLabel.Contains(input.ReLabel.Trim()));
            }
            if (input.MetaFormId!=Guid.Empty)
            {
                predicate = predicate.And(p => p.MetaFormId == input.MetaFormId);
            }

            var result =  _metaFormFieldRepo.GetAllIncluding(p=>p.MetaField).Where(predicate);
            var res = result.OrderBy(p => p.SortNum).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaFormFieldDto>>(res);
            //foreach (var item in resultItems)
            //{
            //    //获取字段信息
            //    var metaFiled = _metaFieldRepo.FirstOrDefault(p => p.Id.ToString()==item.MetaFieldId);
            //    if (metaFiled != null)
            //    {
            //        item.MetaField=ObjectMapper.Map<MetaFieldDto>(metaFiled);
            //    }
            //}
            return new SearchMetaFormFieldOutput { Items = resultItems, TotalCount = totalCount };
        }

        [HttpPost(nameof(DeleteMetaFormField))]
        public async Task<DeleteMetaFormFieldOutput> DeleteMetaFormField(DeleteMetaFormFieldInput input)
        {
            //await _metaFormFieldRepo.DeleteAsync(input.Id);
            //硬删除
            var entity = _metaFormFieldRepo.FirstOrDefault(input.Id);
            await _metaFormFieldRepo.HardDeleteAsync(entity);
            return new DeleteMetaFormFieldOutput();
        }

        /// <summary>
        /// 表单添加字段用：筛选表单可用字段
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost(nameof(SearchMetaFieldForFormField))]
        public async Task<SearchMetaFieldForFormFieldOutput> SearchMetaFieldForFormField(SearchMetaFieldForFormFieldInput input)
        {
            //获取相关对象所有已发布字段
            Expression<Func<MetaField, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.ObjectId))
            {
                predicate = predicate.And(p => p.ObjectId == input.ObjectId);
                predicate = predicate.And(p => p.CurrentStatus == MetaStatus.Released);//已发布字段
            }

            var fields = await _metaFieldRepo.GetAllListAsync(predicate);
            //获取表单内已有字段
            var formFields = await _metaFormFieldRepo.GetAllListAsync(p => p.MetaFormId==input.MetaFormId);
            //获得表单还没有的字段
            var result = fields.Where(p => !formFields.Any(q => q.MetaFieldId==p.Id));
            var res = result.OrderByDescending(p => p.SortNum).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaFieldDto>>(res);
            return new SearchMetaFieldForFormFieldOutput { Items = resultItems, TotalCount = totalCount };
        }

    }
}
